#include "VideoPlayWidget.h"
#include <QMessageBox>

#define WARNING(text) QMessageBox::warning(this, "", text)

VideoPlayWidget::VideoPlayWidget(QWidget *parent)
    : QVideoWidget(parent)
    , m_mediaList(new QMediaPlaylist(this))
    , m_player(new QMediaPlayer(this))
{
    setStyleSheet("VideoPlayWidget {background: black;}");
    setPlayMode(PlayMode::Loop);
}

VideoPlayWidget::~VideoPlayWidget()
{
    if (m_player) {
        m_player->stop();
        delete m_player;
        m_player = nullptr;
    }
    if (m_mediaList) {
        m_mediaList->clear();
        delete m_mediaList;
        m_mediaList = nullptr;
    }
}

void VideoPlayWidget::setPlayMode(PlayMode playMode)
{
    m_mediaList->setPlaybackMode(playMode);
}

void VideoPlayWidget::setPlayList(QStringList fileList)
{
    m_player->stop();
    m_mediaList->clear();
    for (QString file : fileList) {
        m_mediaList->addMedia(QMediaContent(QUrl(file)));
    }
}

void VideoPlayWidget::setMuted(bool mute)
{
    m_player->setMuted(mute);
}

void VideoPlayWidget::play(int id)
{
    m_player->setPlaylist(m_mediaList);
    m_player->setVideoOutput(this);
    if (id != -1) {
        m_mediaList->setCurrentIndex(id);
    }
    try {
        m_player->play();
    } catch (char) {
        WARNING("Lost Video Decode Driver\nPlease Download\nLAV Filters\nfrom Browser");
    }
}

void VideoPlayWidget::stop()
{
    m_player->stop();
    m_mediaList->clear();
}

void VideoPlayWidget::playPrev()
{
    if (!isPlaying()) {
        return;
    }
    int cnt = m_mediaList->mediaCount();
    int curIdx = m_mediaList->currentIndex();
    int dstIdx = (curIdx + cnt - 1) % cnt;
    m_mediaList->setCurrentIndex(dstIdx);
}

void VideoPlayWidget::playNext()
{
    if (!isPlaying()) {
        return;
    }
    int cnt = m_mediaList->mediaCount();
    int curIdx = m_mediaList->currentIndex();
    int dstIdx = (curIdx + 1) % cnt;
    m_mediaList->setCurrentIndex(dstIdx);
}

bool VideoPlayWidget::isPlaying() const
{
    return m_player->state() != QMediaPlayer::State::StoppedState;
}

int VideoPlayWidget::currentId() const
{
    return m_mediaList->currentIndex();
}
